# -*- coding: utf-8 -*-

from types import *

import MySQLdb
import re
import sys
import string
import pprint
import os
import stat
import codecs
import csv
import logging

#from time import gmtime, strftime

#from Cheetah.Template import Template

### singleton but not thread safty

class MySQL:
  
  class __db:
    def __init__(self):
      #fileb = open("../a.ini")
      oneline = "{'host':'localhost','port':'3336','user': 'root', 'password':'myjsy03bjwqt', 'db': 'kylin'}" #fileb.readline()
      mydict  = eval(oneline)
      try:
        self.Con = MySQLdb.connect(host=mydict['host'], port=int(mydict['port']), user=mydict['user'],passwd=mydict['password'], db=mydict['db'])
        self.cursor = self.Con.cursor (MySQLdb.cursors.DictCursor)
        #self.cursor.execute ("set character_set_client = utf8")
        #self.cursor.execute ("set character_set_connection = utf8")
        #self.cursor.execute ("set character_set_results = utf8")
      except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
    
    def execute(self,sql):
      encoding = 'utf8'
      rtn = None
      try:
        cdk = codecs.lookup(encoding)
      except LookupError:
        #print "Lookup Error"
        cdk = None
      
      if cdk:
        sql = sql.encode('utf8')

      
      #print type(sql)
      #print sql
      
      try:
        rtn = self.cursor.execute(sql)
      except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])        
      return rtn
    
    def fetchall(self):
      return self.cursor.fetchall()
      
    def close(self):
      return self.Con.close()
    
  instance = None
  
  def __init__(self):
    if not db.instance:
      db.instance = db.__db()            
    else:
      pass

  def __getattr__(self, name):
    return getattr(self.instance, name)

   
def test():
    tdb = db()
    tdb.execute('show fields from users')
    result_set = tdb.fetchall ()
    if result_set:
      print(str(result_set))
      for item in result_set:
        print(item['Field']) 
        
 


if __name__ == "__main__":
    test()
